/*
    Deferred Shader: Fragment G-buffer Program
 */

uniform sampler2D diffuse_texture;
uniform sampler2D specular_texture;
uniform sampler2D normal_texture;

varying vec3 normal;
varying float depth;
varying vec2 uv;
varying vec2 pack_uv;
varying vec4 mvPos;

varying vec3 TBN1;
varying vec3 TBN2;
varying vec3 TBN3;

// normal mapping switch
uniform int sw_NMAP;
// relief switch
uniform int sw_RELIEF;

// handy
const vec2 CL = vec2(1.0, 0.0);

// apply (inverse) TBN matrix
vec3 iTBN(in vec3 by) {
    vec3 r;
    r.x = dot(TBN1, by);
    r.y = dot(TBN2, by);
    r.z = dot(TBN3, by);
    return r;
}

vec3 TBN(in vec3 by) {
    vec3 r;
    r.x = dot(vec3(TBN1.x, TBN2.x, TBN3.x), by);
    r.y = dot(vec3(TBN1.y, TBN2.y, TBN3.y), by);
    r.z = dot(vec3(TBN1.z, TBN2.z, TBN3.z), by);
    return r;
}

void main() {    
    // specular properties
    vec4 specSample = texture2D(specular_texture, uv);
    float spec = specSample.r;
    float gloss = specSample.a;

    // tangent space normal
    vec4 normalSample = texture2D(normal_texture, uv);
    vec3 ts_normal = normalSample.rgb * 2.0 - 1.0;
    float n_height = normalSample.a * -0.04 + 0.02;    // note we use the negative, for faster calcs later on
    
    vec2 s_uv = uv;
//++if(sw_RELIEF == 1) {
        s_uv = TBN(normalize(mvPos).xyz).xy * n_height + uv;
//++}

    // color
    vec4 color = texture2D(diffuse_texture, s_uv);
    float diff = color.a;
    
    gl_FragData[0] = vec4(color.xyz, normalSample.a);
//++if(sw_NMAP == 1)
        gl_FragData[1] = vec4(iTBN(ts_normal), depth);
//++else
//++    gl_FragData[1] = vec4(normal, depth);

    
    gl_FragData[2] = vec4(diff, spec, gloss, 0.0);
    gl_FragData[3] = mvPos;
}